<template>
  <el-card class="box-card">
    <el-button type="primary" icon="Plus" @click="addTrademark">
      添加品牌
    </el-button>
    <el-table :data="tableData" style="margin: 10px 0" :border="true">
      <el-table-column label="序号" type="index" width="80" align="center" :index="formatIndex()"></el-table-column>
      <el-table-column label="品牌名称" prop="tmName" width="180" align="center"></el-table-column>
      <el-table-column label="品牌logo" align="center">
        <template #default="scope">
          <img :src="scope.row.logoUrl" :alt="scope.row.tmName" style="width: 100px; height: 50px; object-fit: contain" />
        </template>
      </el-table-column>
      <el-table-column label="品牌操作" align="center">
        <!-- @vue-ignore -->
        <template #default="scope">
          <el-button type="warning" icon="Edit" @click="handleEdit(scope.row.id)" />
          <!-- {{ scope.row }} -->
          <!-- 添加确认框 -->
          <el-popconfirm width="220" confirm-button-text="确认" cancel-button-text="取消" icon="InfoFilled" icon-color="red"
            title="确定要删除该词条吗" @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button type="danger" icon="Delete" />
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination style="margin: 10px auto" background layout="prev, pager,next,->,total" :total="total"
      :page-size="limit" :current-page="pageNo" @current-change="handleChange" />
  </el-card>

  <!-- dialog对话框 -->
  <el-dialog v-model="dialogVisible" :title="FormInfo.id ? '修改品牌' : '添加品牌'" width="500" :close-on-click-modal="false"
    @close="closeDialog">
    <el-form style="width: 80%" :model="FormInfo" :rules="rules" ref="formRef">
      <el-form-item label="品牌名称" label-width="100px" prop="tmName">
        <el-input placeholder="请输入品牌名称" v-model="FormInfo.tmName" />
      </el-form-item>
      <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
        <!-- 上传成功 :on-success="handleAvatarSuccess" -->
        <!-- 上传之前 :before-upload="beforeAvatarUpload" -->
        <!-- upload:action 必选参数 ，请求地址-->
        <!-- 对齐文字 -->
        <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="true"
          :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess" :limit="1">
          <img v-if="FormInfo.logoUrl" :src="FormInfo.logoUrl" class="avatar" style="width: 100%; object-fit: cover" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <!-- 传递具名插槽 #footer -->
    <template #footer>
      <div class="dialog-footer" style="background-color: #f7f7f7">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {
  reqGetTrademarkList,
  reqAddUpdateTrademark,
  reqGetTrademarkInfo,
  reqDeleteTrademark,
} from '@/api/product/trademark'
import type {
  Records,
  TradeMark,
  TradeMarkResponseData,
} from '@/api/product/trademark/type.ts'
import { ElMessage, UploadProps } from 'element-plus'
import { ref, reactive, onMounted } from 'vue'
const tableData = ref<Records>([])
const total = ref<number>(0)
const pageNo = ref<number>(1)
// 页面容量
const limit = ref<number>(5)
const dialogVisible = ref<boolean>(false)
const formRef = ref()

// 定义表单收集的信息
const FormInfo = reactive<TradeMark>({
  tmName: '',
  logoUrl: '',
})
// 定义校验规则
const rules = {
  tmName: [
    {
      required: true,
      message: '品牌名称不能为空',
      trigger: 'blur',
    },
  ],
  logoUrl: [
    {
      required: true,
      message: '品牌logo不能为空',
      trigger: 'blur',
    },
  ],
}
const handleChange = (page: number) => {
  pageNo.value = page
  getTrademarkList()
}
onMounted(() => {
  // 页面渲染出来执行
  getTrademarkList()
})
// 图片上传成功之前的钩子 可以约束文件类型和大小 rowfile是当前文件对象
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const isLt2M = rawFile.size / 1024 / 1024 < 4
  if (
    rawFile.type == 'image/jpeg' ||
    rawFile.type == 'image/png' ||
    rawFile.type == 'image/gif'
  ) {
  } else {
    ElMessage.error('上传图片只能是 JPG、PNG、GIF 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 4MB!')
    return false
  }
  return isLt2M
}
// 上传成功的钩子
const handleAvatarSuccess = (res: any) => {
  FormInfo.logoUrl = res.data
  ElMessage.success('上传成功')
  // 触发校验 校验dom对象绑定的logoUrl
  // formRef.value.validateField('logoUrl')
  // 或者清除掉对应的校验项
  formRef.value.clearValidate('logoUrl')
}
// 获取列表
const getTrademarkList = async () => {
  const res: TradeMarkResponseData = await reqGetTrademarkList(
    pageNo.value,
    limit.value,
  )
  total.value = res.data.total
  tableData.value = res.data.records
}
// 格式化index
const formatIndex = () => {
  return (pageNo.value - 1) * limit.value + 1
}
// 关闭对话框
const closeDialog = () => {
  // 关闭对话框
  dialogVisible.value = false
  // 清空数据
  clearForm()
}
// 添加品牌
const addTrademark = () => {
  dialogVisible.value = true
}
// 确定提交
const confirm = () => {
  formRef.value.validate(async (valid: any) => {
    if (!valid) {
      ElMessage.error('请填写完整信息')
      return false
    }
    //提交接口
    const res = await reqAddUpdateTrademark(FormInfo)
    // @ts-ignore
    if (res.code != 200) {
      ElMessage.error(res.data)
      return
    }
    // 刷新列表
    getTrademarkList()
    ElMessage.success(FormInfo.id ? '更新成功' : '添加成功')
    // 清空数据
    closeDialog()
  })
}
// 清空数据和校验信息
const clearForm = () => {
  FormInfo.logoUrl = ''
  FormInfo.tmName = ''
  formRef.value.resetFields()
  delete FormInfo.id
}
// 编辑品牌
const handleEdit = async (id: number) => {
  dialogVisible.value = true
  const res = await reqGetTrademarkInfo(id)
  FormInfo.tmName = res.data.tmName
  FormInfo.logoUrl = res.data.logoUrl
  FormInfo.id = res.data.id
}
// 删除品牌
const handleDelete = async (id: number) => {
  // 弹出对话框
  const res = await reqDeleteTrademark(id)
  // @ts-ignore
  if (res.code == 200) {
    ElMessage.success('删除成功')
    getTrademarkList()
  } else {
    ElMessage.error(res.data)
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  border: 1px dashed #7f7f7f;
  border-radius: 20px;
}
</style>
